import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getSysDictByTypeApi, type DictDTO } from '@/api/system/dict'

export const useDictStore = defineStore('dict', () => {
  // 字典缓存，按字典类型编码存储
  const dictCache = ref<Record<string, DictDTO[]>>({})

  // 获取字典列表
  const getDictList = async (dictTypeCode: string): Promise<DictDTO[]> => {
    // 如果缓存中已有数据，直接返回
    if (dictCache.value[dictTypeCode]) {
      return dictCache.value[dictTypeCode]
    }

    try {
      const response = await getSysDictByTypeApi(dictTypeCode)
      const dictList = response.data || []
      dictCache.value[dictTypeCode] = dictList
      return dictList
    } catch (error) {
      console.error(`获取字典数据失败 (${dictTypeCode}):`, error)
      return []
    }
  }

  // 根据字典类型编码和字典值获取字典名称
  const getDictName = (dictTypeCode: string, dictValue: string | number): string => {
    const dictList = dictCache.value[dictTypeCode] || []
    const dict = dictList.find((item) => item.dictCode === String(dictValue))
    return dict?.dictName || String(dictValue)
  }

  // 根据字典类型编码和字典值获取字典对象
  const getDictItem = (dictTypeCode: string, dictValue: string | number): DictDTO | undefined => {
    const dictList = dictCache.value[dictTypeCode] || []
    return dictList.find((item) => item.dictCode === String(dictValue))
  }

  // 清除指定字典类型的缓存
  const clearDictCache = (dictTypeCode?: string) => {
    if (dictTypeCode) {
      delete dictCache.value[dictTypeCode]
    } else {
      dictCache.value = {}
    }
  }

  // 预加载字典数据
  const preloadDict = async (dictTypeCodes: string[]) => {
    const promises = dictTypeCodes.map((code) => getDictList(code))
    await Promise.all(promises)
  }

  return {
    dictCache: computed(() => dictCache.value),
    getDictList,
    getDictName,
    getDictItem,
    clearDictCache,
    preloadDict
  }
})
